package com.cyl.manager.act.service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyl.manager.act.domain.entity.CouponActivity;
import com.cyl.manager.act.domain.entity.MemberCoupon;
import com.cyl.manager.act.mapper.CouponActivityMapper;
import com.cyl.manager.act.mapper.MemberCouponMapper;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.ruoyi.livesass.ProductVideoService;
import com.volcengine.model.livesaas.response.GetActivityCouponPickDataResponse.ActivityCouponPickData;
import com.volcengine.model.livesaas.response.GetActivityCouponPickDataResponse.GetActivityCouponPickDataResponseBody;

import cn.hutool.json.JSONUtil;

/**
 * 优惠券活动表Service业务层处理
 *
 * @author zcc
 */
@Service
public class CouponActivityBfService {
    @Autowired
    private CouponActivityMapper couponActivityMapper;
    @Autowired
    private MemberCouponMapper memberCouponMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private ProductVideoService productVideoService;
    
    @Autowired
    private CouponActivityBfService couponActivityService;
    
    @Autowired
    private CouponActivityNewService couponActivityNewService;
 
    @Transactional
    public Boolean receiveCouponByTb(Long id,Long memberId) {
        CouponActivity couponActivity = couponActivityNewService.selectCheckById(id);
        if (couponActivity == null) {
           // throw new RuntimeException("未找到活动");
        	return false;
        }
        if (couponActivity.getQlx().intValue() == 2) { // 1福利券 2时长券
            // throw new RuntimeException("券类型不正确");
        	return false;
         }
        //判断有没有余量
        if (couponActivity.getLeftCount() < 1) {
        	return false;
        	// throw new RuntimeException("活动已没有余额");
        }
        //判断时间有没有超
        LocalDateTime now = LocalDateTime.now();
        if (couponActivity.getBeginTime().isAfter(now) || couponActivity.getEndTime().isBefore(now)) {
        	return false;
        	// throw new RuntimeException("活动已过期");
        }
        //判断领的有没有超
        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberId)
                .eq("coupon_activity_id", id);
        Integer count = memberCouponMapper.selectCount(queryWrapper);
        if (count != null && count >= 1) {
        	return false;
        }
        //兑换券
        
        int saveCount = saveMemberCoupon(couponActivity, memberId,1,couponActivity.getQlx()+"","直播间系统补发");
        return saveCount > 0;
    }
 
	public long getLength(long dataSize,long pageSize){
        double length = (double)dataSize/(double)pageSize;
        length = Math.ceil(length);
        long leng = (long) length;
        return leng;
    }
	
    public Map<Long, Boolean> selectMapMemberId(Long activity_id,long conut) {
        Map<Long, Boolean> map = new HashMap<Long, Boolean>();
        long size = 2000;
        long leng  = getLength(conut,size);
        for (int i = 0; i <= leng; i++) {
        	selectPageMemberCoupon(i, size, activity_id, map);
		}
		return map;
        
    }  
    
    public Map<Long, Boolean> selectPageMemberCoupon(long current, long size,Long activity_id,Map<Long, Boolean> map) {
        Page<MemberCoupon> page = new Page<>(current, size);
        page.setOptimizeCountSql(true);
        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("member_id");
        queryWrapper.eq("coupon_activity_id", activity_id);
        Page<MemberCoupon> retPage =  memberCouponMapper.selectPage(page, queryWrapper);
        List<MemberCoupon> list = retPage.getRecords();
         if(list!=null) {
        	for(MemberCoupon memberCoupon : list) {
        		map.put(memberCoupon.getMemberId(), true);
			}
         }
		return map;
    }  
    
    
    public int saveMemberCoupon(CouponActivity activity, Long memberId,Integer count,String lx,String bz) {
        MemberCoupon memberCoupon = new MemberCoupon();
        memberCoupon.setCouponActivityId(activity.getId());
        memberCoupon.setTitle(activity.getTitle());
        memberCoupon.setUseScope(activity.getUseScope());
        memberCoupon.setProductIds(activity.getProductIds());
        memberCoupon.setCouponAmount(activity.getCouponAmount());
        memberCoupon.setMinAmount(activity.getMinAmount());
        memberCoupon.setUseIntegral(activity.getUseIntegral());
        memberCoupon.setCouponType(activity.getCouponType());
        memberCoupon.setBeginTime(LocalDateTime.now());
        memberCoupon.setEndTime(activity.getEndTime());
        memberCoupon.setCreateTime(LocalDateTime.now());
        memberCoupon.setMemberId(memberId);
        memberCoupon.setAmkey(memberId+"_"+activity.getId()+"_"+count);
        memberCoupon.setUseStatus(0);
        memberCoupon.setDeptZbjId(activity.getDeptZbjId());
        memberCoupon.setCouponCategoryId(activity.getCategoryid()); 
        memberCoupon.setLx(lx); //券类型 1福利券 2时长券
        memberCoupon.setBz(bz); //券类型 1福利券 2时长券
        Member member =  memberMapper.selectById(memberId);
        if(member==null) {
        	return 0;
        }
        memberCoupon.setDeptZbjId(member.getDeptZbjId());
        memberCoupon.setDeptTzId(member.getDeptTzId());
        memberCoupon.setDeptDpId(member.getDeptDpId());
        memberCoupon.setSpreaduid(member.getSpreaduid());

       
        return memberCouponMapper.insert(memberCoupon);
    }
 
    //同步已经领取的优惠券
	public int synById(Long yhqid) {
		CouponActivity couponActivity = couponActivityMapper.selectById(yhqid);//查询对象
		Long zbjid = couponActivity.getZbjlid();//那场直播
	    QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
	    queryWrapper.eq("coupon_activity_id", yhqid);
	    long conut = memberCouponMapper.selectCount(queryWrapper);//已经发放的数量
	    long conutSh =getActivityCouponNum(yhqid, zbjid);//火山的数量
	    if(conut >= conutSh) {//数据库多或者大于
	    	 return 0;
	    }   
	    Map<Long, Boolean>  map = selectMapMemberId(yhqid, conut);//数据里面所以的用户id
        int num =  satrtGetActivityCouponPickData(yhqid,zbjid,couponActivity.getTotalCount(),map);//发放操作
        couponActivityMapper.receiveCoupon(yhqid);
        return num;
	}
	
    private int satrtGetActivityCouponPickData(long yhqid, long zbjid, long totalCount,Map<Long, Boolean>  map) {
    	int bfs = 0;
    	return satrtThread(bfs,yhqid,zbjid, totalCount,1,2000,1,map);//发放操作
    }
    
    private Long getActivityCouponNum(long yhqid, long zbjid) {
    	GetActivityCouponPickDataResponseBody responseBody = productVideoService.getGetActivityCouponPickData(yhqid,zbjid, 1, 1);
    	Long tcount = 0L;
    	if(responseBody!=null) {
			 tcount =  responseBody.getTotalCount();
    	}
		return tcount;
    }
    
    private int satrtThread(int bfs,final long yhqid,final long zbjid,final long totalCount,int pageNumber,int pageSize,int num,Map<Long, Boolean>  map) {
    	long sleepm =  1000l;
    	try {
			Thread.sleep(sleepm);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	num = num+1;
    	int xcpageNumber = pageNumber;
    	Long tcount =  0L;
    	GetActivityCouponPickDataResponseBody responseBody = productVideoService.getGetActivityCouponPickData(yhqid,zbjid, pageNumber, pageSize);
		if(responseBody!=null) {
			 tcount =  responseBody.getTotalCount();
			 List<ActivityCouponPickData> hsData = responseBody.getActivityCouponPickData();
			 if(hsData!=null) {
				 if(hsData.size() == pageSize) {//这一页拉取完了下一次拉取下一页
					 xcpageNumber = pageNumber+1;
				 }
				 for (ActivityCouponPickData allData : hsData) {
					try {
						System.err.println("同步数据--" + JSONUtil.toJsonStr(allData));
						long memberId =  Long.parseLong(allData.getExternalUserId());
						if(!map.containsKey(memberId)) {//数据库里面没有数据
							if(memberId>=10000) {//真用户大于10000
								boolean	bool = couponActivityService.receiveCouponByTb(yhqid,memberId);
								if(bool) {
									bfs++;
								}
							}
							
						}
					} catch (Exception e) {
						
					}
				}
			 }
		}
		couponActivityMapper.receiveCoupon(yhqid);//补发一次改一下数据库数量
		if((pageNumber*pageSize) >=  totalCount || (pageNumber*pageSize) >=  tcount) {
			//已经拉取完了
			return bfs;
		}
		return satrtThread(bfs,yhqid,zbjid, totalCount, xcpageNumber, pageSize,num,map); 
	
    }
    
  
    

}
